package com.docjohnson.pamphlet.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.docjohnson.pamphlet.R;
import com.docjohnson.pamphlet.activities.PamphletDetailsActivity;
import com.docjohnson.pamphlet.models.Pamphlet;
import com.docjohnson.pamphlet.utils.ImageDownloadFinishListener;
import com.docjohnson.pamphlet.utils.ImageDownloader;

public class PamphletDetailsFragment extends Fragment {

	private ArrayList<Bitmap> loadedBitmaps = new ArrayList<Bitmap>();
	private ImageDownloader imageDownloader = new ImageDownloader();
	public static PamphletDetailsFragment create(Pamphlet pamphlet) {
		return new PamphletDetailsFragment(pamphlet);
	}

	private Pamphlet pamphlet;
	
	private ArrayList<JSONObject> contentObjectsList = new ArrayList<JSONObject>();

	private PamphletDetailsFragment() {

	}

	private PamphletDetailsFragment(Pamphlet pamphlet) {
		this.pamphlet = pamphlet;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.pamphletdetails, null);
		LinearLayout detailsContainerLayout = (LinearLayout) root.findViewById(R.id.pamphlet_details_container);

		try {
			JSONObject pamphletJson = new JSONObject(pamphlet.getContent());
			Iterator<String> pamphletKeysIterator = pamphletJson.keys();
			while (pamphletKeysIterator.hasNext()) {
				String key = pamphletKeysIterator.next();
				LinearLayout objectContentLayout = new LinearLayout(getActivity().getApplicationContext());
				

				if(pamphletJson != null){
					JSONObject pamphletObject = pamphletJson.getJSONObject(key);
					try {
//						detailsContainerLayout.addView(parsePamphletObject(pamphletObject));
						initPamphletObjects(pamphletObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
			
			Collections.sort(contentObjectsList, new Comparator<JSONObject>() {
		        @Override
		        public int compare(JSONObject s1, JSONObject s2) {
		        	if(s1.optInt("order") > s2.optInt("order"))
		        		return 1;
		        	if(s1.optInt("order") < s2.optInt("order"))
		        		return -1;
		        	return 0;
		        }
		    });
			
			for(JSONObject obj : contentObjectsList){
//				System.out.println("order = "+obj.optInt("order"));
				try {
					detailsContainerLayout.addView(parsePamphletObject(obj));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		root.findViewById(R.id.btn_close).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View btn) {
				btn.setEnabled(false);
				((PamphletDetailsActivity) getActivity()).closePamphlet();
			}
		});

		return root;
	}
	
	private void initPamphletObjects(JSONObject pamphletObject){
		
//		JSONArray pamphletContentObjectsArray = pamphletObject.optJSONArray("content");
//		System.out.println("object = "+pamphletObject);
//		if(pamphletContentObjectsArray == null || pamphletContentObjectsArray.length() == 0){
//			System.out.println("nuuuuuul");
//			return null;
//		}
//		int count = pamphletContentObjectsArray.length();
//		for(int i = 0 ; i < count; i++ ){
//			arrangedItems.add(pamphletContentObjectsArray.optJSONObject(i));
//		}
		Iterator<String> jsonObjectKeys = pamphletObject.keys();
		while(jsonObjectKeys.hasNext()){
			contentObjectsList.add(pamphletObject.optJSONObject(jsonObjectKeys.next()));
		}
		
	}

	/*private View parsePamphletObject(final JSONObject pamphletObject) throws Exception{
		
//		arrangePamphletObjects(pamphletObject);
		String mime = "text/html";
		String encoding = "utf-8";
		
		LinearLayout pamphletObjectContainer = new LinearLayout(getActivity().getApplicationContext());
		pamphletObjectContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		pamphletObjectContainer.setOrientation(LinearLayout.VERTICAL);
		WebView headingTextWebView = new WebView(getActivity().getApplicationContext());
		pamphletObjectContainer.addView(headingTextWebView);
//		headingText.setTextColor(Color.BLACK);
//		headingText.setTypeface(null, Typeface.BOLD);
//		headingText.setTextSize(32);
//		headingText.setGravity(Gravity.CENTER_HORIZONTAL);
		Iterator<String> jsonObjectKeys = pamphletObject.keys();
		while(jsonObjectKeys.hasNext()){
			String key = jsonObjectKeys.next();
			final JSONObject curObject = pamphletObject.optJSONObject(key);
			if ( curObject != null ){
				Iterator<String> curJsonObjectIterator = curObject.keys();
				while (curJsonObjectIterator.hasNext()) {
					final String showingItemType = curJsonObjectIterator.next();
					System.out.println("showingItemType " +showingItemType );
					if("heading".equals(showingItemType)){
//						headingText.setText(curObject.optString(showingItemType));
						headingTextWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
						headingTextWebView.setBackgroundColor(0x00000000);
						headingTextWebView.loadData(curObject.optString(showingItemType), mime, encoding);
					}
					
					if("content".equals(showingItemType) || "features".equals(showingItemType)){
//						TextView contentText = new TextView(getActivity().getApplicationContext());
//						contentText.setText(curObject.optString(showingItemType));
//						contentText.setTextSize(20);
//						contentText.setGravity(Gravity.CENTER_HORIZONTAL);
//						pamphletObjectContainer.addView(contentText);
//						contentText.setTextColor(Color.BLACK);
						WebView contentWebView = new WebView(getActivity());
						contentWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
						contentWebView.setBackgroundColor(0x00000000);
						contentWebView.loadData(curObject.optString(showingItemType), mime, encoding);
						pamphletObjectContainer.addView(contentWebView);
					}
					
					if("imageUrl".equals(showingItemType)){
						LinearLayout imagesContainerLayout = new LinearLayout(getActivity().getApplicationContext());
						final ImageView showingImage = new ImageView(getActivity().getApplicationContext());
						showingImage.setLayoutParams(new LayoutParams(150, 150));
						imagesContainerLayout.addView(showingImage);
						showingImage.post(new Runnable() {
							
							@Override
							public void run() {
								downloadImageToImageView(showingImage, curObject.optString(showingItemType));
							}
						});
						pamphletObjectContainer.addView(imagesContainerLayout);
					}
					
					if("favorites".equals(showingItemType)){
						LinearLayout favoritesContainerLayout = new LinearLayout(getActivity().getApplicationContext());
						favoritesContainerLayout.setOrientation(LinearLayout.VERTICAL);
						JSONArray favoritesArray = null;
						favoritesArray = curObject.getJSONArray(showingItemType);
						if(favoritesArray != null){
							for(int i = 0; i < favoritesArray.length() ; i++){
								JSONObject curFavoriteItem = null;
								curFavoriteItem = favoritesArray.getJSONObject(i);
								if(curFavoriteItem == null){
									continue;
								}
								
								final JSONObject favItemProduct = curFavoriteItem.optJSONObject("product");
								Iterator<String> favoriteKeysIterator = favItemProduct.keys();
								while (favoriteKeysIterator.hasNext()) {
									String curFavoriteObjectKey = favoriteKeysIterator.next();
									
									if(curFavoriteObjectKey.equals("name")){
										TextView favItemNameTextView = new TextView(getActivity().getApplicationContext());
										favItemNameTextView.setText(favItemProduct.optString("name"));
										favItemNameTextView.setTextColor(Color.BLACK);
										underlineText(favItemNameTextView);
										favItemNameTextView.setTextSize(15);
										favItemNameTextView.setOnClickListener(new OnClickListener() {
											
											@Override
											public void onClick(View v) {
												((PamphletDetailsActivity) getActivity()).showFavouriteItem(String.valueOf(pamphlet.getId()), favItemProduct);
											}
										});
										favoritesContainerLayout.addView(favItemNameTextView);
									}
									
								}
							}
						}
						pamphletObjectContainer.addView(favoritesContainerLayout);
					}
				}
			}
		}
		return pamphletObjectContainer;
	}*/
	
	private View parsePamphletObject(final JSONObject object) throws Exception{
				Iterator<String> curJsonObjectIterator = object.keys();
				String mime = "text/html";
				String encoding = "utf-8";
				
				while (curJsonObjectIterator.hasNext()) {
					final String showingItemType = curJsonObjectIterator.next();
//					System.out.println("showingItemType " +showingItemType );
//					if("heading".equals(showingItemType)){
//						headingText.setText(curObject.optString(showingItemType));
//						headingTextWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//						headingTextWebView.setBackgroundColor(0x00000000);
//						headingTextWebView.loadData(curObject.optString(showingItemType), mime, encoding);
//					}
					
					if("content".equals(showingItemType) || "features".equals(showingItemType) || "heading".equals(showingItemType)){
//						TextView contentText = new TextView(getActivity().getApplicationContext());
//						contentText.setText(curObject.optString(showingItemType));
//						contentText.setTextSize(20);
//						contentText.setGravity(Gravity.CENTER_HORIZONTAL);
//						pamphletObjectContainer.addView(contentText);
//						contentText.setTextColor(Color.BLACK);
						WebView contentWebView = new WebView(getActivity());
						contentWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
						contentWebView.setBackgroundColor(0x00000000);
						contentWebView.loadData(object.optString(showingItemType), mime, encoding);
						contentWebView.setBackgroundColor(0x00000000);
						contentWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
						contentWebView.setOnLongClickListener(new OnLongClickListener() {
							@Override
							public boolean onLongClick(View v) {
							    return true;
							}
							});
						contentWebView.setLongClickable(false);
						return contentWebView;
//						pamphletObjectContainer.addView(contentWebView);
					}
					
					if("imageUrl".equals(showingItemType)){
						LinearLayout imagesContainerLayout = new LinearLayout(getActivity().getApplicationContext());
						final ImageView showingImage = new ImageView(getActivity().getApplicationContext());
						showingImage.setLayoutParams(new LayoutParams(150, 150));
						imagesContainerLayout.addView(showingImage);
						showingImage.post(new Runnable() {
							
							@Override
							public void run() {
								downloadImageToImageView(showingImage, object.optString(showingItemType));
							}
						});
						return imagesContainerLayout;
					}
					
					if("favorites".equals(showingItemType)){
						LinearLayout favoritesContainerLayout = new LinearLayout(getActivity().getApplicationContext());
						favoritesContainerLayout.setOrientation(LinearLayout.VERTICAL);
						JSONArray favoritesArray = null;
						favoritesArray = object.getJSONArray(showingItemType);
						if(favoritesArray != null){
							for(int i = 0; i < favoritesArray.length() ; i++){
								JSONObject curFavoriteItem = null;
								curFavoriteItem = favoritesArray.getJSONObject(i);
								if(curFavoriteItem == null){
									continue;
								}
								
								final JSONObject favItemProduct = curFavoriteItem.optJSONObject("product");
								Iterator<String> favoriteKeysIterator = favItemProduct.keys();
								while (favoriteKeysIterator.hasNext()) {
									String curFavoriteObjectKey = favoriteKeysIterator.next();
									
									if(curFavoriteObjectKey.equals("name")){
										TextView favItemNameTextView = new TextView(getActivity().getApplicationContext());
										favItemNameTextView.setText(favItemProduct.optString("name"));
										favItemNameTextView.setTextColor(Color.BLACK);
										underlineText(favItemNameTextView);
										favItemNameTextView.setTextSize(15);
										favItemNameTextView.setOnClickListener(new OnClickListener() {
											
											@Override
											public void onClick(View v) {
												((PamphletDetailsActivity) getActivity()).showFavouriteItem(String.valueOf(pamphlet.getId()), favItemProduct);
											}
										});
										return favItemNameTextView;
									}
								}
							}
						}
					}
				}
									
				return null;				
	}
	
	private void underlineText (TextView textView) {
		  SpannableString content = new SpannableString(textView.getText());
		  content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
		  textView.setText(content);
		}

	private void downloadImageToImageView(final ImageView imageView, String imagePath) {
		imageDownloader.downloadImage(imagePath, Environment.getExternalStorageDirectory().getPath() + "/Pamphlets", imagePath.substring(imagePath.lastIndexOf("/") + 1), new ImageDownloadFinishListener() {

			@Override
			public void onImageDownloaded(String path) {
				Bitmap bmp = BitmapFactory.decodeFile(path);
				imageView.invalidate();
				imageView.setImageBitmap(bmp);
				loadedBitmaps.add(bmp);
				bmp = null;
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		for (int i = 0; i < loadedBitmaps.size(); i++) {
			try {
				loadedBitmaps.remove(0).recycle();
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}
}
